<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="体系id" prop="indicatorSystemId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.indicatorSystemId"-->
      <!--          placeholder="请输入指标体系id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="评价者id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建者" prop="createUser">
        <el-input
          v-model="queryParams.createUser"
          placeholder="请输入创建者名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" size="mini">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:judgement:add']"
        >添加评审任务</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="calSubjectiveWeight"
          v-hasPermi="['system:judgement:calculate']"
          :disabled="ids.length<=0"
        >计算主观权重</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          @click="statusDialog = true"-->
      <!--          :disabled="ids.length<=0"-->
      <!--          v-hasPermi="['system:judgement:edit']"-->
      <!--        >修改状态</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:judgement:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="judgementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="指标体系" align="center" prop="systemName" />
      <el-table-column label="评价者ID" align="center" prop="userId" />
      <el-table-column label="评价矩阵" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.judgeMatrix"
            size="mini"
            type="text"
            @click="handleViewJudgeMatrix(scope.row)"
            v-hasPermi="['system:judgement:view']"
          >查看</el-button>
          <el-button
            v-if="!scope.row.judgeMatrix"
            size="mini"
            type="text"
            @click="handleAddJudgeMatrix(scope.row)"
            v-hasPermi="['system:judgement:mark']"
          >打分</el-button>
        </template>
      </el-table-column>
      <el-table-column label="评价者" align="center" prop="createUser" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tag size="small" :type="statusOptions[scope.row.status].type">{{statusOptions[scope.row.status].label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:judgement:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form :model="queryExpertParams" ref="queryExpertForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="账号名称" prop="userName">
          <el-input
            v-model="queryExpertParams.userName"
            placeholder="请输入账号名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryExpertParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleExpertQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetExpertQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="expertList" @selection-change="handleExpertSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
        <el-table-column label="账号名称" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
        <el-table-column label="角色" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addExpertJudgementTask">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="专家打分"
      :visible.sync="judgeDialogOpen"
      width="80%"
      append-to-body
    >

      <el-descriptions>
        <el-descriptions-item label="评分准则">
          <ol>
            <li>点击下拉框可以选择两个指标的相对权重</li>
            <li>权重分为9、7、5、3、1、1/3、1/5、1/7、1/9一共九个等级，等级值依次减小</li>
            <li>权重等级值越大，表示上方指标的越重要，左方指标越不重要；权重等级值越小，表示上方指标越不重要，左方指标越重要</li>
          </ol>
        </el-descriptions-item>
      </el-descriptions>
      <el-row :gutter="20" style="min-height: 320px">

        <!--  左边表-->
        <el-col :span=10 >

          <el-tree
            :data="currentIndicatorSystem.children"
            node-key="id"
            :expand-on-click-node="false"
            :highlight-current="true"
            default-expand-all
            ref="tree"
            style="overflow:scroll; max-height: 300px; min-height: 300px"
          >
  <span class="custom-tree-node" slot-scope="{ node, data }">
    <div class="flex-container">
      <span>{{ data.indicatorName }}</span>
      <el-button
        size="mini"
        type="text"
        icon="el-icon-search"
        v-show="data.children"
        v-hasPermi="['system:judgement:mark']"
        @click="judgeIndicatorMatrix(data)"
      >打分</el-button>
    </div>
  </span>
          </el-tree>
        </el-col>
        <el-col :span="14" >
          <div class="custom-table">
            <table>
              <thead>
              <tr>
                <!-- 空白单元格 -->
                <th></th>
                <!-- 列标题 -->
                <th v-for="(col, index) in matrixData.colHeader" :key="index">{{ col }}</th>
              </tr>
              </thead>
              <tbody>
              <!-- 行数据 -->
              <tr v-for="(row, rowIndex) in matrixData.data" :key="rowIndex">
                <!-- 行标题 -->
                <td>{{ matrixData.rowHeader[rowIndex] }}</td>
                <!-- 单元格数据 -->
                <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                  <!--                <el-input-number v-model:cell="matrixData.data[rowIndex][cellIndex]"> {{cell}}</el-input-number>-->
                  <el-select v-model="matrixData.data[rowIndex][cellIndex]" placeholder="请选择" style="max-width: 80px"
                             :disabled="canEdit? rowIndex>=cellIndex:true"
                             @change="updateMatrixData(rowIndex,cellIndex)"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!canEdit" type="primary" @click="judgeDialogOpen = false">确 认</el-button>
        <el-button v-if="canEdit" type="primary" @click="addIndicatorSysJudgement">提 交</el-button>
        <el-button v-if="canEdit" @click="judgeDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--    <el-dialog title="修改状态" :visible.sync="statusDialog" width="500px" append-to-body>-->
    <!--      <el-select v-model="status" size="mini">-->
    <!--        <el-option-->
    <!--          v-for="item in statusOptions"-->
    <!--          :key="item.value"-->
    <!--          :label="item.label"-->
    <!--          :value="item.value"-->
    <!--        />-->
    <!--      </el-select>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="handleAudit(status)">确 认</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <el-dialog title="评分结果" :visible.sync="resultDialog" width="80%" append-to-body>
      <el-table v-loading="loading"
                :data="dataList2"
                row-key="id"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                height="500px"
                :style="{overflow: 'scroll'}"
      >
        <el-table-column label="指标名称" align="center" prop="indicatorName" :show-overflow-tooltip="true" class ="tree-field"/>
        <el-table-column label="主观权重" align="center" prop="weight" :show-overflow-tooltip="true" class ="tree-field"/>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-search"
              @click="queryIndicator(scope.row)"
              v-hasPermi="['system:system:indicator']"
            >查看</el-button>
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              type="text"-->
            <!--              icon="el-icon-edit"-->
            <!--              @click="reassignWeightDialog = true; reassignIndicatorWeight(scope.row)"-->
            <!--              v-hasPermi="['system:system:edit']"-->
            <!--              v-if="scope.row.children"-->
            <!--            >重新分配下级指标权重</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doubleCheck">确 定</el-button>
        <el-button @click="resultDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="indicatorDialog" width="800px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="指标名称">
          {{ indicatorVo.indicatorName }}
        </el-descriptions-item>
        <el-descriptions-item label="指标描述">
          {{ indicatorVo.indicatorDescription }}
        </el-descriptions-item>
        <el-descriptions-item label="来源数据">
          {{ indicatorVo.dataSource }}
        </el-descriptions-item>
        <el-descriptions-item label="计算方式">
          {{ indicatorVo.calculationMethod }}
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          {{ indicatorVo.description }}
        </el-descriptions-item>
        <el-descriptions-item label="主观权重">
          {{ indicatorVo.subjectiveWeight }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="indicatorDialog = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="权重调整" :visible.sync="reassignWeightDialog" width="50%" append-to-body>
      <el-table v-loading="loading"
                :data="childrenListVo"
                row-key="id"
                :default-expand-all="false"
                height="500px"
                :style="{overflow: 'scroll'}"
      >
        <el-table-column label="指标名称" align="center" prop="indicatorName" :show-overflow-tooltip="true" class ="tree-field"/>
        <el-table-column label="主观权重" align="center" prop="subjectiveWeight" :show-overflow-tooltip="true" class ="tree-field">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.subjectiveWeight" type="number" step="any"
                      @change="adjustWeightsForSameLevel(childrenListVo, scope.row)" :disabled="!childrenListVo.includes(scope.row)">
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="reassignWeightDialog = false, childrenList = childrenListVo">保存更改</el-button>
        <el-button type="primary" @click="reassignWeightDialog = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listJudgement,
  getJudgement,
  delJudgement,
  addJudgement,
  updateJudgement,
  auditJudgement, generateSubjectiveWeight
} from "@/api/indicator/judgement";
import {getIndicatorBySystemIdAndIndicatorId, search} from "@/api/indicator/system";
import {listUser} from "@/api/system/user";
import {delIndicator, getIndicatorsBySystemId} from "@/api/indicator/indicator";

export default {
  name: "judgement",

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      expertIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      judgementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 评分对话框显示状态，默认为false
      judgeDialogOpen: false,
      // 状态对话框
      statusDialog: false,

      canEdit: false,
      queryExpertParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: 110
      },


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        indicatorSystemId: null,
        userId: null,
        judgeMatrix: null,
        createUser: null,
        modifiedTime: null,
        modifiedName: null,
        status: null
      },
      currentIndicatorSystem: {
        id: null,
        systemName: null,
        children: []
      },
      expertList: [],

      options: [
        { value: 9, label: "9" },
        { value: 7, label: "7" },
        { value: 5, label: "5" },
        { value: 3, label: "3" },
        { value: 1, label: "1" },
        { value: 0.33, label: "1/3" },
        { value: 0.2, label: "1/5" },
        { value: 0.14, label: "1/7" },
        { value: 0.11, label: "1/9" }
      ],
      statusOptions: [
        { value: 0, label: '未采纳', type: 'danger'},
        { value: 1, label: '已采纳' ,type: 'success'},
        { value: 2, label: '待采纳', type: 'warning'},
        { value: 3, label: '待专家评分', type: 'info'}
      ],
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: false },
      ],

      // 评分矩阵数据
      matrixData: {
        data:[],
        rowHeader: [],
        colHeader: []
      },

      indicatorVo: {
        indicatorName: null,
        dataSource: null,
        calculationMethod: null,
        description: null,
        subjectiveWeight: null,
        indicatorLevel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      status: 2,
      handleJudgeId: null,

      resultDialog: false,
      dataList2: [],
      isExpandAll: true,
      indicatorDialog: false,
      childrenListVo: [],
      childrenList: [],
      reassignWeightDialog: false,
      currentTotalWeight: 0,
      resultMap: {}

    };
  },
  created() {
    this.queryParams.indicatorSystemId = this.$route.query.id;
    console.log(this.$route.query);
    this.getList();
  },
  methods: {
    doubleCheck() {
      this.$confirm("是否确认提交评分？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.resultDialog = false;
        auditJudgement(this.$route.query.id, this.resultMap).then(response => {
          this.$message({
            message: "提交成功",
            type: "success"
          });
        })
      });
    },

    updateMatrixData(rowIndex,cellIndex){
      // 获取当前选中的值
      const currentValue = this.matrixData.data[rowIndex][cellIndex];
      // 计算对称位置的值
      let symmetricValue = 1.0 / currentValue;
      // 四舍五入保留两位小数
      if(symmetricValue > 1){
        symmetricValue = parseInt(symmetricValue.toFixed(0));
      }else{
        symmetricValue = parseFloat(symmetricValue.toFixed(2));
      }
      // 更新对称位置的值
      this.matrixData.data[cellIndex][rowIndex] = symmetricValue;
    },

    reassignIndicatorWeight(parent){
      this.childrenList = parent.children;
      this.childrenListVo = JSON.parse(JSON.stringify(parent.children));
    },

    // 记录当前的权重和
    recordCurrentTotalWeight(nodes) {
      this.currentTotalWeight = nodes.reduce((acc, node) => acc + (node.subjectiveWeight || 0), 0);
    },


// 调整同一层次的节点权重，确保权重和为计算得到的totalWeight
    adjustWeightsForSameLevel(nodes, targetNode) {
      const currentTotalWeight = this.childrenList.reduce((acc, node) => acc + (node.subjectiveWeight || 0), 0);
      this.redistributeSubjectiveWeights(targetNode);
      const targetWeight = targetNode.subjectiveWeight;
      const otherNodes = nodes.filter(node => node !== targetNode);
      const totalOtherWeight = otherNodes.reduce((acc, node) => acc + (node.subjectiveWeight || 0), 0);

      // 如果权重和不为计算得到的totalWeight，则进行调整
      if (Math.abs(currentTotalWeight - totalOtherWeight - targetWeight) > Number.EPSILON) {
        const adjustmentFactor = (currentTotalWeight - targetWeight) / totalOtherWeight;
        otherNodes.forEach(node => {
          node.subjectiveWeight *= adjustmentFactor;
          this.redistributeSubjectiveWeights(node);
        });
      }
    },

    // 按比例重新分配子节点的主观权重
    redistributeSubjectiveWeights(parent) {
      const parentWeight = parent.subjectiveWeight || 0;
      let children = parent.children || [];
      const totalChildWeight = children.reduce((acc, child) => acc + (child.subjectiveWeight || 0), 0);

      // 如果子节点的总权重不等于父节点的权重，则按比例重新分配
      if (Math.abs(totalChildWeight - parentWeight) > Number.EPSILON) {
        for (const child of children) {
          // 计算新的权重
          const newWeight = (child.subjectiveWeight / totalChildWeight) * parentWeight;
          child.subjectiveWeight = newWeight;

          // 递归处理子节点
          if (child.children && child.children.length > 0) {
            this.redistributeSubjectiveWeights(child);
          }
        }
      }
    },

    queryIndicator(row){
      getIndicatorBySystemIdAndIndicatorId(this.$route.query.id, row.id).then(response => {
        this.indicatorVo = response.data;
        this.indicatorDialog = true;
      });
    },

    handleAddJudgeMatrix(row){
      this.canEdit = true;
      this.judgeDialogOpen = true;
      this.handleJudgeId = row.id;
      this.handleMatrix();
    },
    addIndicatorSysJudgement(){
      try{
        this.judgeDialogOpen = false;
        this.getList();
        updateJudgement({
          id: this.handleJudgeId,
          indicatorSystemId: this.currentIndicatorSystem.id,
          status: 2,
          judgeMatrix: JSON.stringify(this.currentIndicatorSystem),
        });
        this.$message.success("添加成功");
        this.getList();
      } catch (e){
        this.$message.error("添加失败");
      }
    },
    handleMatrix(){
      this.loading = true;
      getIndicatorsBySystemId(this.$route.query.id).then(response => {
        console.log(response);
        this.currentIndicatorSystem.systemName = this.$route.query.name;
        this.currentIndicatorSystem.id = this.$route.query.id;
        this.currentIndicatorSystem.children = [];
        this.currentIndicatorSystem.children.push({
          id: this.$route.query.id,
          indicatorName: this.$route.query.name,
          children: response.rows
        })
        this.loading = false;
      });
      this.reset();
    },

    addExpertJudgementTask() {
      try{
        let tempList = [];
        console.log(this.expertIds)
        for(let t of this.expertIds){
          tempList.push({
            indicatorSystemId: this.$route.query.id,
            userId: t,
            status: 3
          });
        }
        addJudgement(tempList);
        this.$message({
          type: "success",
          message: "添加成功!"
        });
        this.open = false;
        this.getList();
      } catch (e) {
        this.$message({
          type: "error",
          message: e.toString()
        });
      }
    },


    calSubjectiveWeight() {
      this.reset();
      this.loading = true;
      generateSubjectiveWeight(this.ids).then(response => {
        this.getList();
        if (response.code === 200) {
          this.$message({
            type: "success",
            message: "计算成功!"
          });
          //console.log(response);
          // 确保在请求结束后才设置 resultDialog 和 loading
          this.resultDialog = true;
          // 如果 handleViewIndicatorResult 需要在请求成功后调用，可以放在这里
          //this.handleViewIndicatorResult(response);
          this.dataList2 = response.data.children;
          console.log("DATAlIST",this.dataList2)
          this.resultMap = response.data.resultMap;
          this.loading = false;
        }
      }).catch((error) => {
        this.loading = false;
      });

    },

    handleChangeStatus(row) {
      console.log('状态改变:', row);
      this.status = row.value;
      console.log(this.status)
    },

    judgeIndicatorMatrix(data){
      if(data.judgementMatrix){
        this.matrixData = data.judgementMatrix;
        return;
      }
      data.judgementMatrix={
        rowHeader: [],
        colHeader: [],
        data: []
      };
      for(let i = 0; i < data.children.length; i++){
        console.log(data.children[i].indicatorName);
        data.judgementMatrix.rowHeader.push(data.children[i].indicatorName);
      }
      data.judgementMatrix.colHeader = data.judgementMatrix.rowHeader;
      data.judgementMatrix.data = this.create2DArray(data.children.length, data.children.length);
      this.matrixData = data.judgementMatrix;
    },

    create2DArray(rows, columns) {
      const array2D = new Array(rows);

      for (let i = 0; i < rows; i++) {
        array2D[i] = new Array(columns).fill(1);
      }

      return array2D;
    },
    handleViewJudgeMatrix(row) {
      this.canEdit = false;
      this.currentIndicatorSystem = JSON.parse(row.judgeMatrix);
      this.judgeDialogOpen = true;
    },
    getList() {
      this.loading = true;
      listJudgement(this.queryParams).then(response => {
        this.judgementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        indicatorSystemId: null,
        userId: null,
        judgeMatrix: null,
        createUser: null,
        createTime: null,
        modifiedTime: null,
        modifiedName: null,
        status: null
      };
      this.currentIndicatorSystem={
        id: null,
        systemName: null,
        children: []
      },
        this.matrixData = {
          data:[],
          rowHeader: [],
          colHeader: []
        }
      this.resetForm("form");
    },

    handleViewIndicatorResult(response){
      this.loading = true;
      // getIndicatorsBySystemId(this.$route.query.id).then(response => {
      //   this.dataList2 = response.rows;
      //   this.loading = false;
      // });
      this.dataList2 = response.data;
      this.loading = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleExpertSelectionChange(selection) {
      //console.log(selection)
      this.expertIds = selection.map(item => item.userId)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加评审任务";
      this.getExpert();
    },
    getExpert() {
      this.loading = true;
      listUser(this.addDateRange(this.queryExpertParams, [])).then(response => {
          this.expertList = response.rows;
          this.expertList = this.expertList;
          this.loading = false;
        }
      );
    },

    handleExpertQuery(){
      this.queryExpertParams.pageNum = 1;
      this.queryExpertParams.deptId = 110;
      this.getExpert();
    },
    resetExpertQuery() {
      this.resetForm("queryExpertForm");
      this.queryExpertParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: 110
      };
      this.queryExpertParams.deptId = 110;
      this.$refs.tree.setCurrentKey(null);
      this.handleExpertQuery();
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJudgement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateJudgement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJudgement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function() {
        return delJudgement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleAudit(status) {
      const ids = this.ids;
      this.$modal.confirm('是否确认修改编号为"' + ids + '"的数据项状态？').then(function() {
        return auditJudgement(ids, status);
      }).then(() => {
        this.statusDialog = false;
        this.getList();
        this.$modal.msgSuccess("修改成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/judgement/export', {
        ...this.queryParams
      }, `judgement_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.custom-table table {
  width: 80%;
  border-collapse: collapse;
}

.custom-table th,
.custom-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
}

.custom-table th {
  background-color: #f2f2f2;
}

.custom-table input[type="number"] {
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>
